package com.example.tourstor;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.mysql.jdbc.PreparedStatement;
import com.example.tourstor.view.CitySortModel;
import com.example.tourstor.view.Continent;
import com.example.tourstor.view.EditTextWithDel;
import com.example.tourstor.view.PinyinComparator;
import com.example.tourstor.view.PinyinUtils;
import com.example.tourstor.view.SideBar;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;

public class TravelDestinActivity extends AppCompatActivity {

    private static final String TAG ="TravelDestinActivity" ;
    private ListView sortListView;
    private SideBar sideBar;
    private Continent continent;
    private TextView dialog,title;
    private Button title_btn_left,title_btn_right;
    private SortAdapter4Departure adapter;
    private EditTextWithDel mEtCityName;
    public List<CitySortModel> SourceDateList;
    ArrayList<String> depcity3 = new ArrayList<String>();

    Handler handler;

    String Tdestin,Tstart;
    private Date date1;

    private Button mTv = null;
    private Button bj = null;
    private Button sh = null;
    private Button gz = null;
    private Button sz = null;
    private Button xg = null;
    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_destin);
        setTitle();
        initViews();
    }

    private void initViews() {
        mEtCityName =  findViewById(R.id.et_search);
        sideBar =  findViewById(R.id.sidebar);
        continent = findViewById(R.id.continent);
        dialog =  findViewById(R.id.dialog);
        sortListView = findViewById(R.id.country_lvcountry);

        sortListView.addHeaderView(initHeadView());

        initDatas();
        initEventsLeft();
        //setAdapter();
        title_btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TravelDestinActivity.this,MakePlanActivity.class);
                intent.putExtra("Tdestin",Tdestin);
                setResult(22, intent);
                finish();
            }
        });

    }

    private String setAdapter(final String cnty) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    java.sql.Connection cn = DBOpenHelper.getConn();
                    String sql = "select city from allcity where cnty='"+cnty+"'";
                    Statement st = cn.createStatement();
                    ResultSet rs = st.executeQuery(sql);
                    while (rs.next()) {
                        String depcity = rs.getString("city");
                        depcity3.add(depcity);
                    }
                    cn.close();
                    st.close();
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                Message msg = handler.obtainMessage(5);
                msg.obj = depcity3;
                handler.sendMessage(msg);

            }
        }).start();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 5) {
                    depcity3 = (ArrayList<String>) msg.obj;
                    String[] name =  depcity3.toArray(new String[depcity3.size()]);
                    SourceDateList = filledData(name);
                    Collections.sort(SourceDateList, new PinyinComparator());
                    adapter = new SortAdapter4Departure(TravelDestinActivity.this, SourceDateList);
                    sortListView.setAdapter(adapter);
                }
                super.handleMessage(msg);
            }
        };

        return cnty;

    }

    private void initEventsLeft() {
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position + 1);
                }
            }
        });

        continent.setOnTouchingLetterChangedListener(new Continent.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                if(s.equals("中国")){
                    Log.i(TAG, "onTouchingLetterChanged: 选择的是："+s);
                    continent.setTextColor();
                    setAdapter(s);
                }else if(s.equals("亚洲")){
                    Log.i(TAG, "onTouchingLetterChanged: 选择的是："+s);
                    continent.setTextColor();
                    setAdapter("Japan");
                }
            }
        });

        //ListView的点击事件!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Tdestin =((CitySortModel) adapter.getItem(position - 1)).getName();
                mEtCityName.setText(Tdestin);
            }
        });

        //根据输入框输入值的改变来过滤搜索
        mEtCityName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s!=null){
                    Tdestin=s.toString();
                }

            }
        });
    }


    private void initDatas() {
        sideBar.setTextView(dialog);
    }

    private View initHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.headview, null);

        bj = (Button)headView.findViewById(R.id.BeiJing);

        bj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(bj.getText().toString());
            }
        });
        sh = (Button)headView.findViewById(R.id.ShangHai);

        sh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(sh.getText().toString());

            }
        });
        gz = (Button)headView.findViewById(R.id.GuangZhou);
        gz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(gz.getText().toString());

            }
        });
        sz = (Button)headView.findViewById(R.id.ShenZhen);
        sz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(sz.getText().toString());

            }
        });
        xg = (Button)headView.findViewById(R.id.XiangGang);
        xg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(xg.getText().toString());

            }
        });

        //定位当前城市
        mLocationClient = new LocationClient(this);
        LocationClientOption option = mLocationClient.getLocOption();
        option.setAddrType("all"); //加上这个配置后才可以取到详细地址信息
        mLocationClient.registerLocationListener( myListener );
        mTv = (Button)headView.findViewById(R.id.btn_city_name);
        initLocation();
        mLocationClient.start();
        mTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCityName.setText(mTv.getText().toString());
            }
        });
        return headView;
    }

    private void filterData(String filterStr) {
        List<CitySortModel> mSortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            mSortList = SourceDateList;
        } else {
            mSortList.clear();

            for (CitySortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
                    mSortList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinComparator());
        adapter.updateListView(mSortList);
    }

    private List<CitySortModel> filledData(String[] date) {
        List<CitySortModel> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < date.length; i++) {
            CitySortModel sortModel = new CitySortModel();
            sortModel.setName(date[i]);
            String pinyin = PinyinUtils.getPingYin(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }
            mSortList.add(sortModel);

        }
        Collections.sort(indexString);
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {

            mTv.setText(location.getCity());
            Log.i(TAG, "onReceiveLocation: "+location.getCity());
            if(!location.getCity().equals(null)){
                Toast.makeText(TravelDestinActivity.this,"网络定位成功"+
                        location.getDirection(),Toast.LENGTH_LONG).show();
            }
        }

        //@Override
        public void onReceivePoi(BDLocation arg0) {
        }
    }
    @Override
    public void onDestroy() {
        mLocationClient.stop();
        super.onDestroy();
    }

    /**百度地图定位*/
    //设置相关参数
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
    public void setTitle(){
        title = findViewById(R.id.title_text);
        title.setText("选择地点");

        title_btn_left = findViewById(R.id.title_btn_left);
        title_btn_right=findViewById(R.id.title_btn_right);
        title_btn_left.setText("");

        title_btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

}
